package com.zhx.threadcoreknowledge.stopthread;

/**
 * @author ：zhanghaixuan
 * @date ：Created in 2019-09-29 09:36
 * 用途         ： 在catch 语句中调用 Thread.currentThread().interrupt()中来恢复设置中断状态 ,以便在后续能够检查刚才发生了中断
 * 生产中最佳实践 catch住了InterruptExecption之后的优先选择,在方法签名中抛出异常,
 * 那么在run()就会强制try/catch
 */
public class RightWayStopThreadInProd2 implements Runnable{

    @Override
    public void run() {
        while(true){
            if(Thread.currentThread().isInterrupted()){
                System.out.println("已经被中断了");
                break;
            }

            System.out.println("go");
            reInterrupt();
        }
    }

    private void reInterrupt(){
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RightWayStopThreadInProd2());
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }
}
